<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>频道栏目管理</span>
        <el-button class="button" size="mini" type="text" @click="handleCreateChannel">添加频道</el-button>
      </div>
    </template>
    <el-row class="mb10">
      <el-col :span="24">
        <el-input placeholder="请输入频道名称" v-model.trim="queryList.keyword" size="mini" class="input-w mr10" clearable
          @clear="getDataList" @keyup.enter="getDataList" />
        <el-button type="primary" size="mini" @click="getDataList">
          <el-icon>
            <search />
          </el-icon>
          搜索
        </el-button>
      </el-col>
    </el-row>
    <el-table ref="channelTableRef" :data="tableData.listData" v-loading="isloading" :highlight-current-row="true"
      @row-click="handleClickChannel" :expand-row-keys="expandRowKeys" :row-key="getRowKeys"
      style="width:100%; overflow-y: auto;" border>
      <el-table-column type="expand" @click.stop width="30">
        <template #default="{ row }" class="expandtable">
          <el-table :data="row.columnListData" :show-header="false" :highlight-current-row="true"
            @row-click="handleClickColumn" :ref="el => { if (el) columnTableRef[row.channelid] = el }"
            style="width:100%;">
            <el-table-column width="30"></el-table-column>
            <el-table-column show-overflow-tooltip width="120">
              <template #default="{ row }">
                {{ row.name }}
              </template>
            </el-table-column>
            <el-table-column prop="sort" width="80" align="center" />
            <el-table-column>
              <template #default="{ row }">
                <el-button type="text" size="mini" @click.stop="handleUpdateColumn(row)">编辑</el-button>
                <el-button type="text" size="mini" style="color: red;"
                  @click.stop="handleDeleteColumn(row)">删除</el-button>
              </template>
            </el-table-column>
            <template #empty style="height: 0">
              <span></span>
            </template>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="频道/栏目" prop="name" :show-overflow-tooltip="true" width="120" />
      <el-table-column label="排序" prop="sort" width="80" align="center" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="text" size="mini" @click.stop="handleUpdateChannel(row)">编辑</el-button>
          <el-button type="text" size="mini" style="color: red" @click.stop="handleDeleteChannel(row)">删除</el-button>
          <el-button type="text" size="mini" @click.stop="handleCreateColumn(row)">添加栏目</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <create-channel ref="channelDialogRef" :dialog-visible="dialogChannelVisible"
    :dialog-form-data="dialogChannelFormData" :dialog-status="dialogChannelStatus"
    @handleChannelDialog="handleChannelDialog" @reloadData="getDataList" />
  <create-column ref="columnDialogRef" :dialog-column-visible="dialogColumnVisible"
    :dialog-column-status="dialogColumnStatus" :dialog-column-form-data="dialogColumnFormData" @reloadData="getDataList"
    @handleCancelColumnDialog="handleCancelColumnDialog" />
</template>

<script>
import { ref, reactive, nextTick, toRef, onBeforeUpdate, onMounted, onUnmounted } from 'vue'
import {
  getPackageChannels,
  getPackageChannelColumns,
  deletePackageChannel,
  deletePackageChannelColumn
} from "@/api/package/package";
import CreateChannel from "./CreateChannel";
import CreateColumn from "./CreateColumn";
import { ElMessageBox, ElMessage } from 'element-plus'

export default {
  name: "ChannelColumn",
  components: { CreateChannel, CreateColumn },
  props: {
    packageid: {
      type: Number,
      required: true
    },
    mediaQueryList: {
      type: Object
    },
    columnMediaConfig: {
      type: Object
    }
  },
  emits: ['getChannelMedias', 'getColumnMedias'],
  setup(props, context) {
    const columnTableRef = ref([])
    const queryList = reactive({
      packageid: props.packageid,
      page: 1,
      pagesize: 1000,
      keyword: '',
    })
    const mediaConfig = toRef(props, 'columnMediaConfig')
    const channelMediaQueryList = toRef(props, 'mediaQueryList')
    const tableData = reactive({
      total: 0,
      listData: []
    })
    const isloading = ref(false)
    const channelTableRef = ref(null)

    function setTableAutoHeight() {
      if (channelTableRef.value) {
        // 获取 el-table 的 DOM 元素
        const tableElement = channelTableRef.value.$el;

        const headerHeight = 330;
        const footerHeight = 10;

        const viewportHeight = window.innerHeight || document.documentElement.clientHeight;

        const autoHeight = viewportHeight - headerHeight - footerHeight;

        tableElement.style.height = autoHeight + 'px';
      }
    }

    onMounted(() => {
      setTableAutoHeight()
      window.addEventListener('resize', setTableAutoHeight);
    });

    onUnmounted(() => {
      window.removeEventListener('resize', setTableAutoHeight);
    });

    const dialogChannelVisible = ref(false)
    const dialogChannelStatus = ref('create')
    const dialogChannelFormData = reactive({
      channelid: undefined,
      packageid: props.packageid,
      name: '',
      sort: 1
    })
    const channelDialogRef = ref(null)
    const expandRowKeys = ref([])
    const dialogColumnVisible = ref(false)
    const dialogColumnStatus = ref('create')
    const dialogColumnFormData = reactive({
      channelid: undefined,
      columnid: undefined,
      packageid: undefined,
      name: '',
      sort: 1
    })
    const columnDialogRef = ref(null)

    onBeforeUpdate(() => {
      columnTableRef.value = []
    })

    /** 获取频道列表 **/
    const getDataList = () => {
      isloading.value = true
      getPackageChannels(queryList).then(response => {
        isloading.value = false
        const { total, list } = response.data
        tableData.total = total
        tableData.listData = list
        tableData.listData.forEach(row => {
          getChannelColumns(row)
          expandRowKeys.value.push(row.id)
        })
        if (tableData.listData.length > 0) {
          mediaConfig.value.channelName = tableData.listData[0].name
          channelMediaQueryList.value.channelid = tableData.listData[0].channelid
          getChannelMedias()
          channelTableRef.value.setCurrentRow(tableData.listData[0])
        }
      })
    }
    /** 获取频道栏目列表 **/
    const getChannelColumns = (row) => {
      if (typeof row == 'object') {
        getPackageChannelColumns({ channelid: row.channelid, packageid: props.packageid, page: 1, pagesize: 1000 }).then(response => {
          const { list } = response.data
          row.columnListData = list
        })
      }
    }
    /** 点击频道行展开 **/
    const handleClickChannel = (row) => {
      channelMediaQueryList.value.channelid = row.channelid
      channelMediaQueryList.value.page = 1
      channelMediaQueryList.value.columnid = undefined
      channelMediaQueryList.value.keyword = undefined
      mediaConfig.value.selectedColumn = false
      mediaConfig.value.channelName = row.name
      mediaConfig.value.columnName = undefined
      mediaConfig.value.columnid = undefined
      columnTableRef.value.forEach(ref => {
        ref.setCurrentRow()
      })
      getChannelMedias()
    }
    /** 编辑频道 **/
    const handleUpdateChannel = (row) => {
      dialogChannelFormData.channelid = row.channelid
      dialogChannelFormData.name = row.name
      dialogChannelFormData.sort = row.sort
      dialogChannelStatus.value = 'update'
      dialogChannelVisible.value = true
      nextTick(() => {
        channelDialogRef.value.channelFormRef.clearValidate()
      })
    }
    /** 删除频道 **/
    const handleDeleteChannel = (row) => {
      ElMessageBox.confirm('确定要删除频道 ' + row.name + ' 吗？', '删除频道', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePackageChannel({ channelid: row.channelid }).then(response => {
          if (response.errcode == 0) {
            ElMessage({ type: 'success', message: response.msg, duration: 2000 })
            getDataList()
          }
        })
      }).catch(() => { })
    }
    /** 新建栏目 **/
    const handleCreateColumn = (row) => {
      resetCloumnFormData(row)
      dialogColumnStatus.value = 'create'
      dialogColumnVisible.value = true
      nextTick(() => {
        columnDialogRef.value.columnFormDataRef.clearValidate()
      })

    }
    /** 编辑栏目 **/
    const handleUpdateColumn = (row) => {
      dialogColumnFormData.channelid = row.channelid
      dialogColumnFormData.columnid = row.columnid
      dialogColumnFormData.packageid = props.packageid
      dialogColumnFormData.name = row.name
      dialogColumnFormData.sort = row.sort
      dialogColumnStatus.value = 'update'
      dialogColumnVisible.value = true
      nextTick(() => {
        columnDialogRef.value.columnFormDataRef.clearValidate()
      })
    }
    /** 重置栏目表单 **/
    const resetCloumnFormData = (row) => {
      dialogColumnFormData.columnid = undefined
      dialogColumnFormData.channelid = row.channelid
      dialogColumnFormData.packageid = props.packageid
      dialogColumnFormData.name = ''
      dialogColumnFormData.sort = 1
    }
    /** 新建频道 **/
    const handleCreateChannel = () => {
      resetChannelFormData()
      dialogChannelStatus.value = 'create'
      dialogChannelVisible.value = true
      nextTick(() => {
        channelDialogRef.value.channelFormRef.clearValidate()
      })
    }
    /** 重置频道form表单 **/
    const resetChannelFormData = () => {
      dialogChannelFormData.channelid = undefined
      dialogChannelFormData.name = ''
      dialogChannelFormData.sort = 1
    }
    /** 关闭新建频道弹框 **/
    const handleChannelDialog = () => {
      dialogChannelVisible.value = false
    }
    /** 获取table的rowkey **/
    const getRowKeys = (row) => {
      return row.id
    }
    /** 获取频道栏目媒资列表 **/
    const getChannelMedias = () => {
      context.emit('getChannelMedias')
    }
    /** 获取栏目下媒资列表 **/
    const getColumnMedias = () => {
      context.emit('getColumnMedias')
    }
    /** 点击栏目事件 **/
    const handleClickColumn = (row) => {
      channelMediaQueryList.value.channelid = row.channelid
      channelMediaQueryList.value.columnid = row.columnid
      channelMediaQueryList.value.keyword = undefined
      channelMediaQueryList.value.page = 1
      channelTableRef.value.setCurrentRow()
      columnTableRef.value.forEach((ref, channelid) => {
        if (row.channelid != channelid) {
          ref.setCurrentRow()
        } else {
          ref.setCurrentRow(row)
        }
      })
      mediaConfig.value.selectedColumn = true
      mediaConfig.value.columnid = row.columnid
      tableData.listData.forEach(channel => {
        if (channel.channelid == row.channelid) {
          mediaConfig.value.channelName = channel.name
        }
      })
      mediaConfig.value.columnName = row.name
      getColumnMedias()
    }
    /** 删除栏目 **/
    const handleDeleteColumn = (row) => {
      ElMessageBox.confirm('确定要删除栏目 ' + row.name + ' 吗？', '删除栏目', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePackageChannelColumn({ columnid: row.columnid }).then(response => {
          if (response.errcode == 0) {
            ElMessage({ type: 'success', message: response.msg, duration: 2000 })
            getDataList()
          }
        })
      }).catch(() => { })
    }
    /** 关闭新建栏目弹框 **/
    const handleCancelColumnDialog = () => {
      dialogColumnVisible.value = false
    }

    const init = () => {
      getDataList()
    }

    return {
      queryList,
      tableData,
      init,
      getDataList,
      isloading,
      handleClickChannel,
      channelTableRef,
      setTableAutoHeight,
      handleUpdateChannel,
      handleDeleteChannel,
      handleCreateColumn,
      handleCreateChannel,
      dialogChannelVisible,
      dialogChannelStatus,
      dialogChannelFormData,
      handleChannelDialog,
      channelDialogRef,
      getRowKeys,
      expandRowKeys,
      handleClickColumn,
      dialogColumnFormData,
      dialogColumnStatus,
      dialogColumnVisible,
      handleCancelColumnDialog,
      columnDialogRef,
      handleUpdateColumn,
      handleDeleteColumn,
      columnTableRef
    }
  }
}
</script>

<style lang="scss">
.el-table__empty-block {
  min-height: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-table .el-table__expanded-cell {
  padding: 0;
}
</style>

<style lang="scss" scoped>
.el-table {
  --el-table-header-background-color: transparent;
}
</style>
